package com.sicheng.lc.周赛.分类.秒杀子数组类题目基本原理_前缀和_滑动窗体_数论;

import java.util.HashMap;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/7/11 11:12
 */
public class 和为K的子数组 {

    //https://leetcode.cn/problems/subarray-sum-equals-k/
    public int subarraySum(int[] nums, int k) {
        int sum = 0;
        int cnt = 0;
        HashMap<Integer, Integer> pre = new HashMap<>(32);
        pre.put(0, 1);
        for (int num : nums) {
            sum += num;
            cnt += pre.getOrDefault(sum - k, 0);
            pre.put(sum, pre.getOrDefault(sum, 0) + 1);
        }
        return cnt;
    }
}
